package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.*;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.robert.vesta.util.IdUtils;
import org.asynchttpclient.AsyncCompletionHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/10
 * Time: 8:49 下午
 */
@Service
public class RichCashService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RichCashService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private CeRepaymentLinkDao ceRepaymentLinkDao;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("faircentloan", this);
        BaseJobHandler.merchantAndServiceMap.put("rupeeup", this);
        BaseJobHandler.merchantAndServiceMap.put("koiloan", this);
        BaseJobHandler.merchantAndServiceMap.put("rupeeunion", this);
        BaseJobHandler.merchantAndServiceMap.put("cashwallet", this);
        BaseJobHandler.merchantAndServiceMap.put("cashguide", this);
        BaseJobHandler.merchantAndServiceMap.put("pocketcash", this);
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/merchants/collection/order-list";
        LOGGER.info("== 检测登陆 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);

        if (StringUtils.isEmpty(result)) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return false;
        }

        try {
            Document document = Jsoup.parse(result);
            Elements trs = document.select("table").select("tr");
            if (trs.size() == 0) {
                LOGGER.error("== 请求接口成功 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return false;
            }

        } catch (Exception e) {
            LOGGER.error("== 请求接口数据出错 当前账号登陆异常==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType(), e);
        }

        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {

        updateOrderList(agentAccount);
        updateOrderDetailInfo(agentAccount);
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        int perPage = 50;
        List<RichCashTableElement> items = new ArrayList<>();
        Elements trs = null;
        for (int z = 1; z <= 10; z++) {
            String url = merchant.getApiDomain() + "/merchants/collection/order-list?page=" + z + "&per-page=" + perPage;
            LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
            Map<String, String> headers = getHeaders(agentAccount);
            Map<String, String> params = Maps.newHashMap();
            String result = HttpUtil.getPage(url, params, headers);

            Document document = Jsoup.parse(result);
            trs = document.select("table").select("tr");

            for (int i = 1; i < trs.size(); i++) {
                RichCashTableElement element = new RichCashTableElement();
                Elements tds = trs.get(i).select("td");

                for (int j = 0; j < tds.size(); j++) {
                    if (tds.get(j).childNodes().size() <= 0) {
                        continue;
                    }
                    String value = tds.get(j).childNodes().get(0).toString();

                    if (value.contains("₹")) {
                        value = value.replace("₹", "").replace(",", "").trim();
                    }

                    if (j == 1) {
                        List<Node> nodes = tds.get(j).childNodes();
                        for (int k = 0; k < nodes.size(); k++) {
                            String s = nodes.get(k).toString();
                            if (StringUtils.isNotEmpty(s)) {
                                Document adoc = Jsoup.parse(s);
                                Elements achildTrs = adoc.select("a");
                                if (achildTrs.size() > 0) {
                                    String href = achildTrs.get(0).attributes().get("href");
                                    String key = "collection_id=";
                                    String order_id = "order_id=";
                                    String orderId = "";
                                    if (href.contains(key)) {
                                        orderId = href.substring(href.lastIndexOf(key) + key.length());
                                    } else if (href.contains(order_id)) {
                                        orderId = href.substring(href.lastIndexOf(order_id) + order_id.length());
                                    }
                                    element.setOrderId(orderId);
                                }
                                Document doc = Jsoup.parse(s);
                                Elements childTrs = doc.select("button");
                                if (childTrs.size() > 0) {
                                    String user_id = childTrs.get(0).attributes().get("data-user_id");
                                    element.setUserId(user_id);
                                    break;
                                }

                            }

                        }
                    } else if (j == 2) {
                        element.setProductName(value);
                    } else if (j == 3) {
                        element.setAppName(value);
                    } else if (j == 4) {
                        element.setLoanOrderId(value);
                    } else if (j == 5) {
                        element.setIsReloan(value.equalsIgnoreCase("Yes") ? 2 : 1);
                    } else if (j == 6) {
                        element.setName(value);
                    } else if (j == 7) {
                        element.setPhone(value);
                    } else if (j == 8) {
                        element.setAmount(value);
                    } else if (j == 10) {
                        element.setOverdueDays(value);
                    } else if (j == 11) {
                        element.setLateFee(value);
                    } else if (j == 12) {
                        element.setDueDate(value);
                    } else if (j == 15) {
                        element.setPaidStatus(value);
                    } else if (j == 18) {
                        element.setPaidAmount(value);
                    } else if (j == 19) {
                        element.setRepaymentDate(value);
                    } else if (j == 23) {
                        element.setRecentCollectionRecord(value);
                    }

                }
                if (StringUtils.isNotEmpty(element.getOrderId()) && StringUtils.isNotEmpty(element.getLoanOrderId()) && !element.getAmount().equals("0")) {
                    items.add(element);
                }
            }
            if (trs.size() <= perPage) {
                break;
            }
        }

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        if (items.size() <= 0) {
            if (trs.size() > 0) {
                LOGGER.info("== 当前没有订单 ==，size:{}", items.size());
//                if (activeOrders.size() > 0) {
//                    activeOrders.forEach(ceOrdersEntity -> {
//                        if (ceOrdersEntity.getStatus().equals(OrderStatusEnum.active.getStatus())) {
//                            LOGGER.info("== 订单列表为空，清除库里的active状态数据 ==,orderNo:{}", ceOrdersEntity.getOrderNo());
//                            ceOrdersEntity.setStatus(OrderStatusEnum.removed.getStatus());
//                            ceOrdersEntity.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
//                            ordersDao.updateByPrimaryKey(ceOrdersEntity);
//                        }
//                    });
//                }
            } else {
                LOGGER.info("== 当前账户Token失效 ==，account:{}", agentAccount.getAccount());
            }
            return;
        }


        //如果为空则全部选择插入，这个其实就是初始化数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("==当天没有数活跃数据 开始插入新数据 ==，size:{}", items.size());
            if (agentAccount.getStage().contains("d")) {
                items.forEach(item -> {
                    try {
                        String collectionNo = IdUtils.genId() + "";
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(item.getLoanOrderId())
                                .setOrderInfo(JsonStream.serialize(item))
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(collectionNo);
                        ordersDao.insert(ceOrdersEntity);
                    } catch (Exception e) {
                        LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.getLoanOrderId(), e);
                    }
                });
            } else {
                items.forEach(item -> {
                    try {
                        String orderNo = item.getLoanOrderId();
                        CeOrdersEntity oneByOrderNoAndAgentCode = ordersDao.getOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                        String collectionNo = IdUtils.genId() + "";
                        if (oneByOrderNoAndAgentCode == null) {
                            CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                    .setAgentCode(agentAccount.getAgentCode())
                                    .setMerchantCode(agentAccount.getMerchantCode())
                                    .setOrderNo(item.getLoanOrderId())
                                    .setOrderInfo(JsonStream.serialize(item))
                                    .setStatus(OrderStatusEnum.active.getStatus())
                                    .setCreateDt(new Date())
                                    .setCollectionNo(collectionNo);
                            ordersDao.insert(ceOrdersEntity);
                        } else {
                            LOGGER.info("== 列表为空,订单已存在,更新参数 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                            oneByOrderNoAndAgentCode.setCollectionNo(collectionNo);
                            oneByOrderNoAndAgentCode.setCreateDt(new Date());
                            oneByOrderNoAndAgentCode.setSyncStatus(OrderSyncStatusEnum.waiting.getStatus());
                            oneByOrderNoAndAgentCode.setOrderInfo(JsonStream.serialize(item));
                            ordersDao.insert(oneByOrderNoAndAgentCode);
                        }

                    } catch (Exception e) {
                        LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.getLoanOrderId(), e);
                    }
                });
            }

        } else {
            //更新数据
            LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());
            Map<String, CeOrdersEntity> activeOrdersMap = new HashMap<>();
            Set<String> newOrdersSet = new HashSet<>();
            activeOrders.forEach(o -> {
                activeOrdersMap.put(o.getOrderNo(), o);
            });
            items.forEach(item -> {
                String loanId = item.getLoanOrderId();
                newOrdersSet.add(loanId);
            });

            //如果更新之后发现有新的订单了，则继续插入
            items.forEach(item -> {
                try {
                    String loanId = item.getLoanOrderId();
                    if (!activeOrdersMap.containsKey(loanId)) {
                        LOGGER.info("==更新的时候发现有新的订单==,account:{},loanId:{}", agentAccount.getAccount(), loanId);

                        CeOrdersEntity oneByOrderNo = ordersDao.getTodayOneByOrderNo(loanId);
                        if (oneByOrderNo == null) {
                            CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                    .setAgentCode(agentAccount.getAgentCode())
                                    .setMerchantCode(agentAccount.getMerchantCode())
                                    .setOrderNo(item.getLoanOrderId())
                                    .setOrderInfo(JsonStream.serialize(item))
                                    .setStatus(OrderStatusEnum.active.getStatus())
                                    .setCreateDt(new Date())
                                    .setCollectionNo(IdUtils.genId() + "");
                            ordersDao.insert(ceOrdersEntity);
                        } else {
                            LOGGER.info("==更新的时候发现有新的订单 该订单已经存在==,account:{},loanId:{}", agentAccount.getAccount(), loanId);
                        }
                    }

                } catch (Exception e) {
                    LOGGER.error("== 更新数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.getLoanOrderId(), e);
                }
            });

            //如果跟新之后发现数据比原来的少了，则需要更新订单状态
            activeOrdersMap.keySet().forEach(activeOrderNo -> {
                try {
                    if (!newOrdersSet.contains(activeOrderNo)) {
                        LOGGER.info("== 更新的时候发现有订单消失 目前认为是订单状态发生了改变 ==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo);
                        CeOrdersEntity ceOrdersEntity = activeOrdersMap.get(activeOrderNo);
                        if (ceOrdersEntity.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            ceOrdersEntity.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(ceOrdersEntity);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.info("==更新的时候发现有订单 异常==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo, e);
                }
            });
        }

        LOGGER.info("== 订单刷新处理完成 ==");

    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> dialHeaders = getHeaders(agentAccount);
        dialHeaders.put("X-Requested-With", "XMLHttpRequest");
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                String orderId = orderInfo.get("orderId").toString();
                Map<String, String> infoMap = new HashMap<>();
                String baseInfoUrl = merchant.getApiDomain() + "/merchants/collection/view?collection_id=" + orderId;
                String baseInfo = HttpUtil.getPage(baseInfoUrl, params, headers);
                LOGGER.info("== 获取成功 repaymentInfo==");


                Document document = Jsoup.parse(baseInfo);
                Elements tables = document.select("tbody");
                if (tables.size() <= 0) {
                    return;
                }
                Elements rptrs = tables.get(1).select("tr");
                RcRepaymentInfoVo rcRepaymentInfoVo = new RcRepaymentInfoVo();
                for (int i = 0; i < rptrs.size(); i++) {
                    Elements tds = rptrs.get(i).select("td");
                    for (int j = 0; j < tds.size(); j++) {
                        if (tds.get(j).childNodes().size() <= 0) {
                            continue;
                        }
                        String value = tds.get(j).childNodes().get(0).toString();
                        if (value.contains("₹")) {
                            value = value.replace("₹", "").replace(",", "").trim();
                        }
                        if (i == 0 && j == 0) {
                            rcRepaymentInfoVo.setOrderId(value);
                        } else if (i == 0 && j == 1) {
                            rcRepaymentInfoVo.setLoanAmount(value);
                        } else if (i == 0 && j == 2) {
                            rcRepaymentInfoVo.setLateFee(value);
                        } else if (i == 0 && j == 3) {
                            rcRepaymentInfoVo.setTotalRepayment(value);
                        } else if (i == 1 && j == 0) {
                            rcRepaymentInfoVo.setOverdueDays(value);
                        } else if (i == 1 && j == 1) {
                            rcRepaymentInfoVo.setDeductAmount(value);
                        } else if (i == 1 && j == 2) {
                            rcRepaymentInfoVo.setPaidAmount(value);
                        } else if (i == 1 && j == 3) {
                            rcRepaymentInfoVo.setRemainingAmount(value);
                        } else if (i == 2 && j == 0) {
                            rcRepaymentInfoVo.setLoanTime(value);
                        } else if (i == 2 && j == 1) {
                            rcRepaymentInfoVo.setPeriod(value);
                        } else if (i == 2 && j == 2) {
                            rcRepaymentInfoVo.setCost(value);
                        } else if (i == 2 && j == 3) {
                            rcRepaymentInfoVo.setDueTime(value);
                        } else if (i == 3 && j == 0) {
                            rcRepaymentInfoVo.setBankCard(value);
                        } else if (i == 3 && j == 1) {
                            rcRepaymentInfoVo.setRepaymentStatus(value);
                        }
                    }
                }
                String repaymentInfoJson = JsonStream.serialize(rcRepaymentInfoVo);
                infoMap.put("repaymentInfo", repaymentInfoJson);

                String remainMoney = rcRepaymentInfoVo.getRemainingAmount();
                updateRemainMoney(order.getCollectionNo(), remainMoney);

                if (!hasDetailData) {
                    CeOrdersDetailEntity personalInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "personalInfo", order.getOrderNo());
                    if (personalInfoDetail == null) {
                        Elements trs = tables.get(0).select("tr");
                        RichCashBasicData richCashBasicData = new RichCashBasicData();
                        for (int i = 0; i < trs.size(); i++) {
                            Elements tds = trs.get(i).select("td");
                            for (int j = 0; j < tds.size(); j++) {
                                if (tds.get(j).childNodes().size() <= 0) {
                                    continue;
                                }
                                String value = tds.get(j).childNodes().get(0).toString();

                                if (i == 0 && j == 0) {
                                    richCashBasicData.setName(value);
                                } else if (i == 0 && j == 1) {
                                    richCashBasicData.setContactDetails(value);
                                } else if (i == 0 && j == 2) {
                                    richCashBasicData.setGender(value);
                                } else if (i == 0 && j == 3) {
                                    richCashBasicData.setAge(value);
                                    if (StringUtils.isNotEmpty(value)) {
                                        richCashBasicData.setBirthDay(getBirthDayByAge(Integer.parseInt(value)));
                                    } else {
                                        richCashBasicData.setBirthDay(getBirthDayByAge(99));
                                    }
                                } else if (i == 1 && j == 0) {
                                    richCashBasicData.setEducation(value);
                                } else if (i == 1 && j == 1) {
                                    richCashBasicData.setMarriage(value);
                                } else if (i == 1 && j == 2) {
                                    richCashBasicData.setAadhaarNo(value);
                                } else if (i == 2 && j == 0) {
                                    richCashBasicData.setCompanyName(value);
                                } else if (i == 2 && j == 1) {
                                    richCashBasicData.setCompanyAddress(value);
                                } else if (i == 2 && j == 2) {
                                    richCashBasicData.setCompanyPhone(value);
                                } else if (i == 3 && j == 1) {
                                    richCashBasicData.setUsualAddress(value);
                                } else if (i == 4 && j == 0) {
                                    List<Node> nodes = tds.get(j).childNodes();
                                    ArrayList<String> list = Lists.newArrayList();
                                    for (int k = 0; k < nodes.size(); k++) {
                                        String s = nodes.get(k).toString();
                                        if (StringUtils.isNotEmpty(s)) {
                                            Document doc = Jsoup.parse(s);
                                            Elements childTrs = doc.select("a");
                                            if (childTrs.size() > 0) {
                                                String href = childTrs.get(0).attributes().get("href");
                                                list.add(href);
                                            }
                                        }
                                    }
                                    ImagesVo imagesVo = new ImagesVo();
                                    if (list.size() == 3) {
                                        imagesVo.setAadhaarBackImage(list.get(0));
                                        imagesVo.setAadhaarFrontImage(list.get(1));
                                        imagesVo.setSelfieImage(list.get(2));
                                    }
                                    richCashBasicData.setImagesVo(imagesVo);
                                }
                            }
                        }
                        LOGGER.info("== 获取成功 personalInfo==");
                        infoMap.put("personalInfo", JsonStream.serialize(richCashBasicData));
                        infoMap.put("images", JsonStream.serialize(richCashBasicData.getImagesVo()));
                    } else {
                        personalInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(personalInfoDetail);
                    }
                    CeOrdersDetailEntity emergencyContactInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "emergencyContactInfo", order.getOrderNo());
                    if (emergencyContactInfoDetail == null) {
                        Elements contactTrs = tables.get(3).select("tr");
                        try {
                            if (contactTrs.size() > 0) {
                                JSONArray contacts = new JSONArray();
                                for (int i = 0; i < contactTrs.size(); i++) {
                                    Elements tds = contactTrs.get(i).select("td");
                                    JSONObject j1 = new JSONObject();
                                    for (int j = 0; j < tds.size(); j++) {
                                        if (tds.get(j).childNodes().size() <= 0) {
                                            continue;
                                        }
                                        String value = tds.get(j).childNodes().get(0).toString();
                                        if (j == 2) {
                                            j1.put("name", value);
                                        } else if (j == 3) {
                                            j1.put("phone", value);
                                        }

                                    }
                                    if (j1.get("phone") != null) {
                                        contacts.add(j1);
                                    }
                                }
                                infoMap.put("emergencyContactInfo", contacts.toString());
                            }

                        } catch (Exception e) {
                            LOGGER.error("== 紧急联系人转换错误 ==", e);
                        }
                    } else {
                        emergencyContactInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(emergencyContactInfoDetail);
                    }
                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        try {
                            JSONArray callList = new JSONArray();
                            int pageSize = 50;
                            for (int i = 1; i <= 10; i++) {
                                String dialUrl = merchant.getApiDomain() + "/merchants/collection/view?collection_id=" + orderId + "&page=" + i + "&per-page=" + pageSize;
                                String dialInfo = HttpUtil.getPage(dialUrl, params, dialHeaders);
                                Document dialDocument = Jsoup.parse(dialInfo);
                                Elements dialTables = dialDocument.select("tbody");
                                if (dialTables.size() <= 0) {
                                    continue;
                                }
                                Elements dialTrs = dialTables.get(0).select("tr");
                                for (int j = 0; j < dialTrs.size(); j++) {
                                    JSONObject call = new JSONObject();
                                    Elements tds = dialTrs.get(j).select("td");
                                    for (int k = 0; k < tds.size(); k++) {
                                        if (tds.get(k).childNodes().size() <= 0) {
                                            continue;
                                        }
                                        String value = tds.get(k).childNodes().get(0).toString();
                                        if (k == 1) {
                                            call.put("name", value);
                                        } else if (k == 2) {
                                            String replace = value.replace("-", "");
                                            if (replace.contains("+91")) {
                                                replace = value.replace("+91", "");
                                            }
                                            call.put("phone", replace);
                                        }
                                    }
                                    callList.add(call);
                                }
                                LOGGER.info("======" + dialTrs.size());
                                if (dialTrs.size() < pageSize) {
                                    break;
                                }
                            }

                            JSONObject jsonData = new JSONObject();
                            jsonData.put("contacts", callList);

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                            infoMap.put("contactUrl", contactUrl);

                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });

                    order.setSyncStatus(OrderSyncStatusEnum.waiting.getStatus());
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("productName").toString().trim() + "[" + orderDetail.get("appName").toString().trim() + "]";
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");

                CeOrdersDetailEntity emergencyContactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "emergencyContactInfo", order.getOrderNo());
                Any emergencyContactInfoJson = JsonIterator.deserialize(emergencyContactInfo.getDetailInfo());

                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "personalInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                CeOrdersDetailEntity repaymentInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfoJson = JsonIterator.deserialize(repaymentInfo.getDetailInfo());

                CeOrdersDetailEntity contactUrl = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                Any contactUrlJson = JsonIterator.deserialize(contactUrl.getDetailInfo());

                String borrowCapital = repaymentInfoJson.get("loanAmount").toString();
                String overdueDays = repaymentInfoJson.get("overdueDays").toString();
                String lateFee = repaymentInfoJson.get("lateFee").toString();


                String overdueRatio = "0";
                String serviceFee = repaymentInfoJson.get("cost").toString();
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                String paidAmount = repaymentInfoJson.get("paidAmount").toString();
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(1)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest("0")
                        .setDeductAmount(repaymentInfoJson.get("deductAmount").toString())
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(new BigDecimal(borrowCapital).subtract(new BigDecimal(serviceFee)).toString())
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(repaymentInfoJson.get("loanTime").toString())
                        .setRepaymentDate(repaymentInfoJson.get("dueTime").toString())
                        .setRemainMoney(repaymentInfoJson.get("remainingAmount").toString())
                        .setTotalMoney(repaymentInfoJson.get("totalRepayment").toString());

                //surplus_money
                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());

                String pancardNo = "no-data";
                String aadhaarNo = personalInfoJson.get("aadhaarNo").toString();
                String email = "no-data";

                String companyCity = "no-data";
                String companyProvince = "no-data";
                String friendName = "no";
                String friendMobile = "no";

                String parentName = "no";
                String parentPhone = "no";

                List<Any> anies = emergencyContactInfoJson.asList();
                String personMobile = personalInfoJson.get("contactDetails").toString();
                String personName = personalInfoJson.get("name").toString();

                if ("no".equalsIgnoreCase(parentName)) {
                    if (anies.size() >= 2) {
                        parentName = anies.get(0).get("name").toString();
                        parentPhone = anies.get(0).get("phone").toString();
                        friendName = anies.get(1).get("name").toString();
                        friendMobile = anies.get(1).get("phone").toString();
                    }
                }

                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                Map<String, Any> stringAnyMap = JsonIterator.deserialize(iamges.getDetailInfo()).asMap();

                List<String> images = new ArrayList<>();
                stringAnyMap.values().forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(personalInfoJson.get("usualAddress").toString())
                        .setBirthday(personalInfoJson.get("birthDay").toString())
                        .setCity(companyCity)
                        .setState(companyProvince)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(0)
                        .setKycNo(aadhaarNo)
                        .setMobile(personMobile)

                        .setMarriedStatus(0)
                        .setName(personName)
                        .setPinCode("no")

                        .setSex(personalInfoJson.get("gender").toInt())
                        .setContactUrl(contactUrlJson.toString())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        Map<String, String> params = Maps.newHashMap();
        String url = merchant.getApiDomain() + "/merchants/collection/order-list?page=1&per-page=50&type=3";
        LOGGER.info("== 开始请求已还款订单列表 ==,url:{}", url);
        String result = HttpUtil.getPage(url, params, headers);
        Document document = Jsoup.parse(result);
        Elements trs = document.select("table").select("tr");
        if (trs.size() <= 0) {
            LOGGER.info("== 请求已还款订单列表出错 ==,account:{}", agentAccount.getAccount());
            return;
        }
        waitingPaidCheckOrders.forEach(order -> {
            boolean isRepay = false;
            for (int i = 1; i < trs.size(); i++) {
                Elements tds = trs.get(i).select("td");

                for (int j = 0; j < tds.size(); j++) {
                    if (tds.get(j).childNodes().size() <= 0) {
                        continue;
                    }
                    String value = tds.get(j).childNodes().get(0).toString();

                    if (j == 4) {
                        if (order.getOrderNo().equals(value)) {
                            isRepay = true;
                            break;
                        }
                    } else if (j > 4) {
                        break;
                    }

                }
                if (isRepay) {
                    break;
                }
            }
            if (isRepay) {
                LOGGER.info("== 获取成功 还清 标记为需要结清==,orderNo:{}", order.getOrderNo());
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } else {
                LOGGER.info("== 获取成功 没有还清 订单移除或者展期 不做操作==,orderNo:{}", order.getOrderNo());

                //                HashMap<String, String> header = Maps.newHashMap();
//                Any orderDetails = JsonIterator.deserialize(order.getOrderInfo());
//                String page = HttpUtil.getPage("https://miwallet.hengyaruiyi.com/merchants/collection/generate-renew-url?user_id="+orderDetails.get("userId").toString()+"&order_id="+orderDetails.get("orderId").toString(),Maps.newHashMap() ,header);
//                String shortUrl = JsonIterator.deserialize(page).get("data").get("shortUrl").toString();
//                String s = com.jy.bo.common.conf.util.HttpUtil.getOkHttpGet(shortUrl);
//                LOGGER.info("====", s);
//
//                Document doc = Jsoup.parse(s);
//                Elements childTrs = doc.select("form");
//                if (childTrs.size() > 0) {
//                    String action = childTrs.get(0).attributes().get("action");
//                    LOGGER.info("==该订单存在action，可以进行展期 ==,action:{}", action);
//                    LOGGER.info("====", action);
//                    String userId="user_id=";
//                    if (action.contains(userId)){
//                        String id = action.substring(action.lastIndexOf(userId) + userId.length());
//                        if (id.equals(order.getOrderNo())){
//                            LOGGER.info("==该订单未进行展期，认为被移除==,action:{}", id);
//                        }
//                    }
//                }else {
//                    LOGGER.info("==该订单不存在action，无法再次进行展期 ==");
//                    Elements errorChildTrs = doc.select("p");
//                    if (errorChildTrs.size() > 0) {
//                        String tip = errorChildTrs.get(0).childNodes().get(0).toString();
//                        LOGGER.info("== 无法再次进行展期,部分还款订单 ==,tip:{}", tip);
//                        order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
//                        order.setStatus(OrderStatusEnum.paid_update.getStatus());
//                        ordersDao.updateByPrimaryKey(order);
//                    }
//                }

            }

        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
                String paidAmount = deserialize.get("paidAmount").toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount(deserialize.get("deductAmount").toString())
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });

    }

    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
//                String paidAmount = deserialize.get("paidAmount").toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });

    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("called_person_type", "0");
        jsonObject.put("operate_type", "1");
        jsonObject.put("result_type", "91");
        jsonObject.put("result_reason", "61");
        ceCommentPushLogEntity.setPushDetail(jsonObject.toString());

        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    /**
     * @param ceCommentPushLogEntity
     * @return 1 connected   1-7 willingness-to-repay
     * 1-11 willing to repay
     * 1-5 虚假个人信息
     * 2  no-answer
     * 3  empty-number / halt / shutdown
     * 4  reject / hang-up / pull-black
     */
    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        LOGGER.info("== 开始同步催记到甲方 ==");
        RichCashCollectionTagEnum currentTag = RichCashCollectionTagEnum.RNR_V2;

        for (RichCashCollectionTagEnum e : RichCashCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }

        try {
            CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
            CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
            CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceCommentPushLogEntity.getMerchantCode(), "personalInfo", ceCommentPushLogEntity.getOriginNo());

            CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(personalInfo.getOrderNo());
            Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
            Any pushDetail = JsonIterator.deserialize(ceCommentPushLogEntity.getPushDetail());
            Any deserialize = JsonIterator.deserialize(account.getRequestHeader());
            String url = ceMerchantEntity.getApiDomain() + "/merchants/collection/collect-loan?collection_id=" + orderInfo.get("orderId").toString();
            AsyncHttpClient c = new DefaultAsyncHttpClient();
            Future<Response> f = c.prepareGet(url)
                    .addFormParam("CollectLoanForm[contact_phone]", "")
                    .addFormParam("CollectLoanForm[promise_repayment_time]", "")
                    .addFormParam("CollectLoanForm[called_person_type]", pushDetail.get("called_person_type").toString())
                    .addFormParam("CollectLoanForm[operate_type]", pushDetail.get("operate_type").toString())
                    .addFormParam("CollectLoanForm[discuss_result]", String.valueOf(currentTag.getCpType()))
                    .addFormParam("CollectLoanForm[remark]", currentTag.getShortDesc())
                    .addFormParam("CollectLoanForm[result_type]", pushDetail.get("result_type").toString())
                    .addFormParam("CollectLoanForm[result_reason]", pushDetail.get("result_reason").toString())
                    .addFormParam("collection_id", orderInfo.get("orderId").toString())
                    .addHeader("Cookie", deserialize.get("Cookie").toString())
                    .addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE)
                    .execute(new AsyncCompletionHandler<Response>() {
                        @Override
                        public void onThrowable(Throwable t) {
                            throw new RuntimeException("exception");
                        }

                        @Override
                        public Response onCompleted(Response response) {
                            return response;
                        }
                    });
            long startTime = System.currentTimeMillis();
            Response response;
            while (true) {
                response = f.get();
                if (response != null) {
                    break;
                } else {
                    long endTime = System.currentTimeMillis();
                    // 大于8秒认为查询数据失败
                    if ((endTime - startTime) / 1000 > 8) {
                        throw new RuntimeException("exception");
                    }
                }
            }
            String responseBody = response.getResponseBody();
            if (JsonIterator.deserialize(responseBody).get("code").toInt() != 0) {
                LOGGER.info("== RichCash 开始同步催记到甲方 异常==,res:{}", responseBody);
            }
            return "0".equals(JsonIterator.deserialize(responseBody).get("code").toString());
        } catch (Exception e) {
            LOGGER.info("== cbcash 开始同步催记到甲方 异常==", e);
            return false;
        }
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());

        CeOrdersDetailEntity repaymentInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceOrdersEntity.getMerchantCode(), "repaymentInfo", ceOrdersEntity.getOrderNo());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        Any repaymentInfoJson = JsonIterator.deserialize(repaymentInfo.getDetailInfo());
        String link = "";
        Map<String, String> headers = getHeaders(accountEntity);
        HashMap<String, String> params = Maps.newHashMap();
        params.put("user_id", orderInfoJson.get("userId").toString());
        params.put("order_id", orderInfoJson.get("loanOrderId").toString());
        params.put("amount", String.valueOf(new BigDecimal(repaymentInfoJson.get("totalRepayment").toString()).multiply(new BigDecimal(100)).toBigInteger()));
        String url = ceMerchantEntity.getApiDomain() + "/merchants/collection/generate-repay-url";
        LOGGER.info("== 获取还款链接请求  RichCash== url:{},params:{}", url, JsonStream.serialize(params));

        String result = HttpUtil.getPage(url, params, headers);
        Any resultJson = JsonIterator.deserialize(result);
        if (!"".equals(resultJson.get("data").toString())) {
            link = resultJson.get("data").get("shortUrl").toString();
            LOGGER.info("== 获取还款链接 ==,link:{}", link);
        } else {
            LOGGER.error("== 获取还款链接失败 ==,account:{},loanId:{}", ceOrdersEntity.getAgentCode(), ceOrdersEntity.getOrderNo());
        }

        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());

        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        String renewLink = "";
        Map<String, String> headers = getHeaders(accountEntity);
        HashMap<String, String> renewParams = Maps.newHashMap();
        renewParams.put("user_id", orderInfoJson.get("userId").toString());
        renewParams.put("order_id", orderInfoJson.get("loanOrderId").toString());
        String renewUrl = ceMerchantEntity.getApiDomain() + "/merchants/collection/generate-renew-url";
        LOGGER.info("== 获取展期还款链接请求  RichCash== renewUrl:{},renewParams:{}", renewUrl, JsonStream.serialize(renewParams));

        String renewResult = HttpUtil.getPage(renewUrl, renewParams, headers);
        Any renewResultJson = JsonIterator.deserialize(renewResult);

        if (!"".equals(renewResultJson.get("data").toString())) {
            renewLink = renewResultJson.get("data").get("shortUrl").toString();
            LOGGER.info("== 获取展期还款链接 ==,renewLink:{}", renewLink);
        }
        return renewLink;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }

    public static String getLastDayDate(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(DateUtil.getDate(date, "yyyy-MM-dd"));
        c.add(Calendar.DATE, -1);
        Date start = c.getTime();
        return format.format(start);
    }

    @Override
    public String queryPaymentOrderResult(String orderNo,String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(ordersEntity.getAgentCode());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(ordersEntity.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();

        String url = merchant.getApiDomain() + "/merchants/collection/order-list?page=1&per-page=50&type=3";
        LOGGER.info("== 开始请求已还款订单列表 ==,url:{}", url);
        String result = HttpUtil.getPage(url, params, headers);
        Document document = Jsoup.parse(result);
        Elements trs = document.select("table").select("tr");
        if (trs.size() <= 0) {
            LOGGER.info("== 请求已还款订单列表出错 ==,account:{}", agentAccount.getAccount());
            return "no order found";
        }
        boolean isRepay = false;
        for (int i = 1; i < trs.size(); i++) {
            Elements tds = trs.get(i).select("td");

            for (int j = 0; j < tds.size(); j++) {
                if (tds.get(j).childNodes().size() <= 0) {
                    continue;
                }
                String value = tds.get(j).childNodes().get(0).toString();

                if (j == 4) {
                    if (ordersEntity.getOrderNo().equals(value)) {
                        isRepay = true;
                        break;
                    }
                } else if (j > 4) {
                    break;
                }

            }
            if (isRepay) {
                break;
            }
        }
        if (isRepay) {
            LOGGER.info("== 获取成功 还清 标记为需要结清==,orderNo:{}", ordersEntity.getOrderNo());
            if (!ordersEntity.getSyncStatus().equals(OrderSyncStatusEnum.pay_update_success.getStatus())) {
                ordersEntity.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
            }
            ordersEntity.setStatus(OrderStatusEnum.paid_update.getStatus());
            ordersDao.updateByPrimaryKey(ordersEntity);
            return "paid already!";
        }

        return "no paid";
    }

    public static void main(String[] args) {

        HashMap<String, String> header = Maps.newHashMap();
        header.put("Cookie", "_csrf-merchant=b7f198cabc373c1244c984a49e5de7d46352834bb89b3b35866641051a6e1716a%3A2%3A%7Bi%3A0%3Bs%3A14%3A%22_csrf-merchant%22%3Bi%3A1%3Bs%3A32%3A%22KswJanCJXaKo0CpYC3PAm3-jwQK1HVfY%22%3B%7D; site_language=in; advanced-merchant-new=4vn3mvv2lgip3p3h5vc9osies5");
        String page = HttpUtil.getPage("https://miwallet.hengyaruiyi.com/merchants/collection/generate-renew-url?user_id=409442&order_id=508269", Maps.newHashMap(), header);
        String shortUrl = JsonIterator.deserialize(page).get("data").get("shortUrl").toString();
        String s = com.jy.bo.common.conf.util.HttpUtil.getOkHttpGet(shortUrl);
        LOGGER.info("====", s);

        Document doc = Jsoup.parse(s);
        Elements childTrs = doc.select("form");
        if (childTrs.size() > 0) {
            String action = childTrs.get(0).attributes().get("action");
            LOGGER.info("==该订单存在action，可以进行展期 ==", action);
            LOGGER.info("====", action);
            String userId = "user_id=";
            if (action.contains(userId)) {
                String id = action.substring(action.lastIndexOf(userId) + userId.length());
                if (id.equals("363945")) {
                    LOGGER.info("==该订单未进行展期，认为被移除==", action);
                }
            }
        } else {
            LOGGER.info("==该订单不存在action，无法再次进行展期 ==");
            Elements errorChildTrs = doc.select("p");
            if (errorChildTrs.size() > 0) {
                String tip = errorChildTrs.get(0).childNodes().get(0).toString();
                LOGGER.info("== 无法再次进行展期 ==", tip);
            }
        }
    }

    private static String getBirthDayByAge(Integer age) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.YEAR, -age);
        Date y = c.getTime();
        return format.format(y);
    }
}
